package com.bndg.browser.db

import android.content.Context
import androidx.room.Database
import androidx.room.Room.databaseBuilder
import androidx.room.RoomDatabase
import kotlin.concurrent.Volatile

@Database(entities = [History::class, InputHistory::class], version = 2)
abstract class AppDatabase : RoomDatabase() {

    abstract fun historyDao(): HistoryDao
    abstract fun inputHistoryDao(): InputHistoryDao

    companion object {
        @Volatile
        private var INSTANCE: AppDatabase? = null

        fun getInstance(context: Context): AppDatabase {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
            }
        }

        private fun buildDatabase(context: Context): AppDatabase {
            return databaseBuilder(
                context.applicationContext,
                AppDatabase::class.java,
                "browser.db"
            )
                .addMigrations() // 添加迁移策略（如果需要）
                .fallbackToDestructiveMigration() // 如果没有提供迁移策略，则删除并重建数据库
                .build()
        }
    }
}
